package com.example.repository;

import com.example.model.User;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.stereotype.Repository;

import java.io.IOException;

@Repository
public class UserRepository {

    private static final String TABLE_NAME = "users";
    private static final byte[] CF_CREDENTIALS = Bytes.toBytes("credentials");
    private static final byte[] COL_PASSWORD = Bytes.toBytes("password");
    private static final byte[] COL_ROLE = Bytes.toBytes("role");

    private final Table userTable;

    public UserRepository(Connection connection) throws IOException {
        this.userTable = connection.getTable(TableName.valueOf(TABLE_NAME));
    }

    public User findByUsername(String username) throws IOException {
        Get get = new Get(Bytes.toBytes(username));
        Result result = userTable.get(get);
        if (result.isEmpty()) {
            return null;
        }
        return mapToUser(result);
    }

    public void create(User user) throws IOException {
        Put put = new Put(Bytes.toBytes(user.getUsername()));
        put.addColumn(CF_CREDENTIALS, COL_PASSWORD, Bytes.toBytes(user.getPassword()));
        if (user.getRole() != null) {
            put.addColumn(CF_CREDENTIALS, COL_ROLE, Bytes.toBytes(user.getRole()));
        }
        userTable.put(put);
    }

    public void deleteByUsername(String username) throws IOException {
        Delete delete = new Delete(Bytes.toBytes(username));
        userTable.delete(delete);
    }

    private User mapToUser(Result result) {
        String username = Bytes.toString(result.getRow());
        byte[] passwordBytes = result.getValue(CF_CREDENTIALS, COL_PASSWORD);
        if (passwordBytes == null) {
            return null;
        }
        String password = Bytes.toString(passwordBytes);
        
        byte[] roleBytes = result.getValue(CF_CREDENTIALS, COL_ROLE);
        String role = (roleBytes != null) ? Bytes.toString(roleBytes) : null;
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        return user;
    }
} 